package com.ziji.rocketmq.general;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @author <a href="mailto:ziji.zhao@aliyun.com">ziji</a>
 * @since 2021/11/12
 */
public class SomeConsumer {
    public static void main(String[] args) throws MQClientException {
        // 定义一个 Pull 消费者, 参数为 Consumer Group 名称
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("cg");
        // 指定 Name Server
        consumer.setNamesrvAddr("localhost:9876");
        // 指定从第一条消息开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        // 指定消费 topic 和 tag
        consumer.subscribe("someTopic", "*");
//        consumer.subscribe("someTopic", "someTag1");
//        // 指定采用"广播模式"进行消费，默认采用"集群模式"
//        consumer.setMessageModel(MessageModel.BROADCASTING);
//        // 修改消费重试次数
//        consumer.setMaxReconsumeTimes(2);

        // 注册消息监听
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            // 一旦 broker 中有了其订阅的消息就会触发该方法的执行
            // 其返回值是当前 consumer 消费的状态
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    System.out.println(msg);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
//                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        consumer.start();
        System.out.println("Consumer Started!");
    }
}




















